import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [{
        path: 'index',
        name: 'index',
        meta: { title: 'index' },
        component: () =>
            import ('../views/index.vue'),
        children: [{
                path: '/index/home',
                name: 'home',
                meta: { title: '主页' },
                component: () =>
                    import ('../views/index/Home.vue')
            }, {
                path: '/index/order',
                name: 'order',
                meta: { title: '订单' },
                component: () =>
                    import ('../views/index/Order.vue')
            }, {
                path: '/index/bao',
                name: 'bao',
                meta: { title: '爆爆团' },
                component: () =>
                    import ('../views/index/Bao.vue')
            }, {
                path: '/index/mine',
                name: 'mine',
                meta: { title: '我的' },
                component: () =>
                    import ('../views/index/Mine.vue')
            }, {
                path: '/index',
                redirect: '/index/home',
            },
            {
                path: '*',
                component: () =>
                    import ('../views/NotFound.vue')
            }
        ]

    },
    {
        path: '/',
        redirect: '/index'
    },
    {
        path: '*',
        component: () =>
            import ('../views/NotFound.vue')
    },
    {
        path: '/register',
        name: 'register',
        meta: { title: '注册' },
        component: () =>
            import ('../views/Register.vue')
    },
    {
        path: '/login',
        name: 'login',
        meta: { title: '登陆' },
        component: () =>
            import ('../views/login.vue'),
        //路由独享的守卫函数
        // beforeEnter: (to, from, next) => {
        //   console.log('beforeEnter');
        //   next();
        // }
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
router.beforeEach((to, from, next) => {
    document.title = to.meta.title;
    var token = localStorage.getItem('token');
    //对于后台管理系统这种应用, 只有登录页是可以随意访问的, 但是其他所有页面都是必须在登陆以后才可以访问
    if (to.path == '/register') { //跳往 注册页 , 允许跳转
        next();
    } else {
        if (to.path == '/login') { //跳往 登录页
            if (token) { //已登录 , 重定向到 "/"
                next('/');
            } else { //未登录 , 允许跳往 登录页
                next();
            }
            // next();
        } else { //跳往 非登录页
            if (token) { //已登录 , 允许访问
                next();
            } else { //未登录 , 重定向到 "/login"
                next('/login');
            }
        }
    }
})
export default router